package com.lunatic.rocketmq.demo;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.remoting.protocol.heartbeat.MessageModel;

public class RocketMQConsumer {
    public static void main(String[] args) throws Exception {
        // 1. 初始化消费者
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumer_group");
        consumer.setNamesrvAddr("192.168.101.106:9876");
        consumer.subscribe("TestTopic", "*");
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
        // 默认集群模式，一个消费者组中的多个消费者共同处理一次消息
        consumer.setMessageModel(MessageModel.BROADCASTING);
        // 广播模式。不再关心消费者组，所有消费者都可以收到消息
//        consumer.setMessageModel(MessageModel.CLUSTERING);

        // 2. 注册消息监听器（使用 Lambda 表达式）
        consumer.registerMessageListener((MessageListenerConcurrently) (
                msgs, context)
                -> {
            msgs.forEach(msg -> {
                System.out.printf("Received message: %s%n", new String(msg.getBody()));
            });
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        });

        // 3. 启动消费者
        consumer.start();
        System.out.println("Consumer started. Press Enter to exit.");
        System.in.read();
        consumer.shutdown();
    }
}